/*
 * main.cpp
 *
 *  Created on: 11-May-2011
 *      Author: tan-ce
 */

#include <iostream>
#include "tcetools/socket.h"
#include "tcetools/basic_http.h"

using namespace std;
using namespace tcetools;

int main(int argc, char *argv[]) {
	cout << "Hello. Build 20110518-1" << endl;

	ListenerSocket ls("8080", 2);
	BasicHttpDigestAuthInfo auth("Testing");

	auth.add_user("tance", "qazwsx");
	cout << ("tance:Testing:qazwsx") << endl
		 << auth.HA1["tance"] << endl;

	while (1) {
		ServerSocket *ss = ls.accept_connection();
		BasicHttpServer http(ss);

		http.enable_digest_auth(auth);
		http.process_request();

		cout << "Client requesting ";

		if (http.get_req_type() == BasicHttpServer::REQ_GET) cout << "GET";
		if (http.get_req_type() == BasicHttpServer::REQ_POST) cout << "POST";

		cout << " for " << http.get_uri() << endl;

		for (BasicHttp::field_map_iter i = http.request_fields.begin();
				i != http.request_fields.end(); ++i) {
			cout << "\t" << i->first << " --> " << i->second << endl;
		}

		if (http.get_req_type() == BasicHttpServer::REQ_POST) {
			cout <<   "--- POST DATA ---\n"
				 << http.raw_post_data
				 << "\n-----------------" << endl;

			for (BasicHttp::field_map_iter i = http.post_data.begin();
					i != http.post_data.end(); ++i) {
				cout << "\t" << i->first << " --> " << i->second << endl;
			}
		}

		if (!http.active()) continue;

		cout << "Sending Hello World" << endl;

		http.set_data("Hello World Two!");

		http.reply(BasicHttpServer::STATUS_OK, "OK");
	}
}
